﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DataAccessLib;
using System.Linq;
using DevExpress.XtraEditors.Controls;

namespace ePharmacyLauch
{
    public partial class Xuatban : BaseForm
    {
        private NhaThuocModelDataContext context = new NhaThuocModelDataContext();

        private DataTable table;

        
        public decimal ThanhTien 
        {
            get 
            { 
                decimal tt = 0m;
                return tt;
            }    
        }

        public Xuatban()
        {
            InitializeComponent();
        }

        private void txtNamSinh_Validated(object sender, EventArgs e)
        {

        }
        public bool load_customer_process()
        {
            //string txtCus_ = txtTen.Text.Trim();

            return true;
        }

        private void Xuatban_Load(object sender, EventArgs e)
        {
            InitControls();
            BindControls();
            cbKhachHang.Focus();
        }

        private void InitControls() 
        {
            this.cbDvt.Properties.AutoComplete = true;
            this.cbDvt.Properties.DropDownRows = 10;
            this.cbDvt.Properties.ImmediatePopup = true;

            this.cbTenThuoc.Properties.AutoComplete = true;
            this.cbTenThuoc.Properties.DropDownRows = 20;
            this.cbTenThuoc.Properties.ImmediatePopup = true;


            this.cbMaThuoc.Properties.AutoComplete = true;
            this.cbMaThuoc.Properties.DropDownRows = 20;
            this.cbMaThuoc.Properties.ImmediatePopup = true;

            //this.cbKhachHang.Properties.AutoComplete = true;
            this.cbKhachHang.Properties.DropDownRows = 20;
            this.cbKhachHang.Properties.ImmediatePopup = true;

            this.teSoTien.Properties.Mask.BeepOnError = true;
            this.teSoTien.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
            this.teSoTien.Properties.Mask.EditMask = "############,#0";
            this.teSoTien.Properties.Mask.IgnoreMaskBlank = true;
            this.teSoTien.Properties.Mask.SaveLiteral = true;
            this.teSoTien.Properties.Mask.UseMaskAsDisplayFormat = true;

            //init table
            this.InitTable();

            

            //
            this.cbMaThuoc.Focus();
        }

        private void InitTable()
        {
            this.table = new DataTable("tbHoaDon");
            this.table.Columns.Add("MaThuoc", typeof(int));
            this.table.Columns.Add("TenThuoc", typeof(string));
            this.table.Columns.Add("SoLuong", typeof(decimal));
            this.table.Columns.Add("DonVi", typeof(string));
            this.table.Columns.Add("DonGia", typeof(decimal));
        }

        private void BindControls() 
        {
            var donViList = this.context.DonVis.ToList();
            foreach (var dv in donViList)
            {
                this.cbDvt.Properties.Items.Add(dv.TenDonVi);
                this.repComboDVT.Items.Add(dv.TenDonVi);
            }
            this.cbDvt.SelectedText = "Viên";
            //this.repComboDVT.SelectedText = "Viên";

            var thuocList = this.context.Thuocs.ToList();
            foreach (var t in thuocList)
            {
                this.cbTenThuoc.Properties.Items.Add(t.TenThuoc);
                this.cbMaThuoc.Properties.Items.Add(t.Id);
            }

            var goiThuocList = this.context.GoiThuocs.ToList();
            foreach (var gt in goiThuocList)
                this.cbGoiThuoc.Properties.Items.Add(gt.TenGoi);


            var khList = this.context.KhachHangs.ToList();

            this.cbKhachHang.Properties.DataSource = khList;

            //foreach (var kh in khList)
            //    this.cbKhachHang.Properties.Items.Add(kh.TenKhachHang);

            this.gridControl1.DataSource = this.table;

            
        }

        private void cbKhachHang_Properties_KeyPress(object sender, KeyPressEventArgs e)
        {
            
        }

        private void cbKhachHang_Properties_Leave(object sender, EventArgs e)
        {
            var cb = (LookUpEdit)sender;
            
            if (!string.IsNullOrEmpty(cb.Text))
            {
                try
                {
                    var val = (KhachHang)cb.GetSelectedDataRow();
                    //var first  = this.context.KhachHangs.FirstOrDefault(x => x.Id == val.Id);
                    this.txtNamSinh.Text = val.NamSinh.ToString();
                }
                catch
                {
                }
            }
        }

        private void cbKhachHang_Properties_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Tab) 
            //{
            //    e.SuppressKeyPress = true;    
            //}
            //if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab) SendKeys.Send("{Tab}{F4}");
        }

        private void btThem_Click(object sender, EventArgs e)
        {
            
        }

        private void DoInsert() 
        {
            var result = this.DoValidate();
            if (result == string.Empty)
            {
                Insert();
                this.teThanhTien.Text = ThanhTien.ToString();
                ClearControls();
                this.cbMaThuoc.Focus();
            }
            else
            {
                MessageBox.Show(result);
            }
        }

        private void Insert()
        {
            var row = this.table.NewRow();
            int maThuoc;
            decimal soTien, soLuong;
            
            if (!int.TryParse(this.cbMaThuoc.Text.Trim(), out maThuoc))
            {
                MessageBox.Show("Mã thuốc không đúng định dạng");
                return;
            }
            if (!decimal.TryParse(this.teSoTien.Text.Trim(), out soTien))
                soTien = 0m;
            if (!decimal.TryParse(this.calcSoLuong.Text.Trim(), out soLuong))
                soLuong = 0;

            row.ItemArray = new object[] { 
                maThuoc,
                this.cbTenThuoc.Text.Trim(),
                soLuong,
                this.cbDvt.Text.Trim(),
                soTien
            };

            this.table.Rows.Add(row);
        }

        private string DoValidate() 
        {
            if (string.IsNullOrEmpty(this.cbTenThuoc.Text) || string.IsNullOrEmpty(this.cbMaThuoc.Text))
                return "Xin nhập tên thuốc";
            if (string.IsNullOrEmpty(this.cbDvt.Text))
                return "Xin nhập đơn vị tính";
            if (string.IsNullOrEmpty(this.calcSoLuong.Text))
                return "Xin nhập số lượng";
            //if (string.IsNullOrEmpty(this.teSoTien.Text))
            //    return "Xin nhập số tiền";

            return string.Empty;
        }

        private void ClearControls() 
        {
            this.cbMaThuoc.Text = string.Empty;
            this.cbTenThuoc.Text = string.Empty;
            this.cbDvt.Text = "Viên";
            //this.calcSoLuong.Text = "0";
            this.teSoTien.Text = "";
            this.calcSoLuong.Text = string.Empty;
        }

        private void teSoTien_Properties_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                DoInsert();
            }
        }

        private void cbMaThuoc_Properties_Leave(object sender, EventArgs e)
        {
            var cb = (ComboBoxEdit)sender;
            if (!string.IsNullOrEmpty(cb.Text))
            {
                int maThuoc;
                var parseResult = int.TryParse(cb.Text, out maThuoc);
                if (!parseResult)
                    return;
                var first = this.context.Thuocs.FirstOrDefault(x => x.Id == maThuoc);
                if (first != null)
                    this.cbTenThuoc.Text = first.TenThuoc;
            }
        }

        private void cbTenThuoc_Properties_Leave(object sender, EventArgs e)
        {
            var cb = (ComboBoxEdit)sender;
            if (!string.IsNullOrEmpty(cb.Text))
            {
                var tenThuoc = cb.Text.Trim();
                var first = this.context.Thuocs.FirstOrDefault(x => x.TenThuoc == tenThuoc);
                if (first != null)
                    this.cbMaThuoc.Text = first.Id.ToString();
            }
        }

        private void labelControl2_Click(object sender, EventArgs e)
        {

        }

        private void labelControl7_Click(object sender, EventArgs e)
        {

        }

        private void ucButton1_ButtonClick(object sender, EventArgs e)
        {
            
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private void b8Delete_Click(object sender, EventArgs e)
        {
            DoDelete();
        }

        private void DoDelete() 
        {
            if (this.table == null || this.table.Rows.Count == 0)
            {
                MessageBox.Show("Đơn hàng rỗng");
                return;
            }

            this.gridView1.DeleteSelectedRows();
            //this.teThanhTien.EditValue = ThanhTien;
        }

        private void DoUpdate() 
        {
            
            if (this.table == null || this.table.Rows.Count == 0)
                MessageBox.Show("Đơn hàng chưa có thuốc. Xin nhập thuốc.");
            else
            {
                //=============== insert Khach Hang ==============
                int maKH = 0;
                int namSinh;
                if (this.cbKhachHang.Text.Trim() == string.Empty){
                    MessageBox.Show("Xin nhập đầy đủ thông tin khách hàng.");
                    this.cbKhachHang.Focus();
                    return;
                }

                if (this.txtNamSinh.Text.Trim() == string.Empty) {
                    MessageBox.Show("Xin nhập đầy đủ thông tin khách hàng.");
                    this.txtNamSinh.Focus();
                    return;
                }

                if (this.teThanhTien.Text.Trim() == string.Empty) {
                    MessageBox.Show("Chưa nhập thành tiền hóa đơn.");
                    this.teThanhTien.Focus();
                    return;
                }
                
                var khObj = this.context.KhachHangs.FirstOrDefault(x => x.TenKhachHang == this.cbKhachHang.Text.Trim() && x.NamSinh == int.Parse(this.txtNamSinh.Text.Trim()));
                if (khObj == null)
                {
                    try
                    {
                        var kh = new KhachHang
                        {
                            TenKhachHang = this.cbKhachHang.Text.Trim(),
                            NamSinh = int.Parse(this.txtNamSinh.Text.Trim()),
                            DiaChi = string.Empty
                        };
                        this.context.KhachHangs.InsertOnSubmit(kh);
                        this.context.SubmitChanges();
                        maKH = kh.Id;
                    }
                    catch {
                        MessageBox.Show("Lỗi thêm khách hàng. Xin kiểm tra lại");
                        return;
                    }
                }

                maKH = khObj != null ? khObj.Id : maKH;

                try
                {
                    //=============== insert DonHang =================
                    var dh = new DonHang
                    {
                        GhiChu = this.mmGhiChu.Text,
                        MaKhachHang = maKH,
                        SoTien = decimal.Parse(this.teThanhTien.Text.Trim()),
                        //NgayLapHD = DateTime.Now
                    };

                    this.context.DonHangs.InsertOnSubmit(dh);
                    this.context.SubmitChanges();
                    var maDonHang = dh.Id;

                    //=============== insert CTDonHang ================
                    foreach (DataRow row in this.table.Rows)
                    {
                        var ctdh = new CTDonHang
                        {
                            MaThuoc = (int)row["MaThuoc"],
                            MaDonHang = maDonHang,
                            MaDonVi = (int) FindMaDonVi(row["DonVi"].ToString()),
                            SoLuong = (decimal)row["SoLuong"]
                        };

                        this.context.CTDonHangs.InsertOnSubmit(ctdh);
                    }
                    this.context.SubmitChanges();

                }
                catch(Exception ex) {
                    MessageBox.Show(ex.ToString());
                    return;
                }

                MessageBox.Show("Đã thêm thành công");
                DoCleanup();
            }
        }

        private void DoCleanup() 
        {
            this.cbKhachHang.Text = string.Empty;
            this.txtNamSinh.Text = string.Empty;
            this.teThanhTien.Text = string.Empty;
            this.mmGhiChu.Text = string.Empty;
            this.cbGoiThuoc.Text = string.Empty;
            this.cbMaThuoc.Text = string.Empty;
            this.cbTenThuoc.Text = string.Empty;
            this.cbDvt.Text = "Viên";
            this.calcSoLuong.Text = string.Empty;
            this.cbMaThuoc.Focus();

            this.table.Rows.Clear();
            this.table.AcceptChanges();

            this.gridControl1.DataSource = table;
        }
        public void Clearup_grid()
        {
            this.table.Rows.Clear();
            this.table.AcceptChanges();
        }


        private void b8Save_Click(object sender, EventArgs e)
        {
            DoUpdate();
            InitControls();
            BindControls();
            cbKhachHang.Focus();
        }

        private int FindMaDonVi(string tenDonVi)
        {
            var first = this.context.DonVis.First(x => x.TenDonVi == tenDonVi);
            if (first != null)
                return first.Id;
            return -1;
        }

        private void comboBoxEdit1_Properties_KeyDown(object sender, KeyEventArgs e)
        {
            var combo = (ComboBoxEdit)sender;
            if (e.KeyData == Keys.Enter)
            {
                var goiId = FindGoiThuocId(combo.Text.Trim());
                if (goiId == 0)
                {
                    MessageBox.Show("Không tìm thấy gói thuốc thích hợp.");
                    return;
                }

                var GoiTH = this.context.GoiThuocs.First(x => x.Id == goiId);

                if (GoiTH != null)
                {
                    teThanhTien.Text = GoiTH.Gia.ToString();
                    mmGhiChu.Text = GoiTH.MoTa.ToString();

                    var thuocList = (from ctgt in this.context.CTGoiThuocs
                                     join t in this.context.Thuocs on ctgt.MaThuoc equals t.Id
                                     join dv in this.context.DonVis on ctgt.MaDonVi equals dv.Id
                                     where ctgt.MaGoiThuoc == goiId
                                     select new
                                     {
                                         MaThuoc = t.Id,
                                         TenThuoc = t.TenThuoc,
                                         DonVi = dv.TenDonVi,
                                         SoLuong = ctgt.SoLuong
                                     }).Distinct().ToList();

                    foreach (var t in thuocList)
                    {
                        var r = this.table.NewRow();
                        r.ItemArray = new object[] { 
                        t.MaThuoc, t.TenThuoc, t.SoLuong, t.DonVi
                    };
                        this.table.Rows.Add(r);
                    }

                    this.gridControl1.DataSource = this.table;
                }                
            }
        }

        private int FindGoiThuocId(string tenGoiThuoc)
        {
            var first = this.context.GoiThuocs.First(x => x.TenGoi == tenGoiThuoc);
            if (first != null)
                return first.Id;
            return 0;
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            //this.teThanhTien.EditValue = ThanhTien;
        }

        private void btLayHD_Click(object sender, EventArgs e)
        {
            if (cbKhachHang.Text == "")
            {
                MessageBox.Show("Nhập tên khách hàng để lấy lại toa thuốc");
                return;
            }
            else if (txtNamSinh.Text == "")
            {
                MessageBox.Show("Chọn năm sinh của khách hàng");
                return;
            }

            Clearup_grid();
            string txtKhachhang = this.cbKhachHang.Text.Trim();           
            int txtNamsinh_ = int.Parse(this.txtNamSinh.Text.Trim());

            var firstKh = this.context.KhachHangs.FirstOrDefault(x => x.TenKhachHang == txtKhachhang && x.NamSinh == txtNamsinh_);
            if (firstKh == null) 
            {
                MessageBox.Show("Không tìm thấy thông tin hóa đơn từ khách hàng đã nhập.");
                return;    
            }
            var hd = (from dh in this.context.DonHangs
                     where dh.MaKhachHang == firstKh.Id
                     orderby dh.NgayLapHD descending
                     select dh).FirstOrDefault();
            if (hd != null)
            {
                teThanhTien.Text = hd.SoTien.ToString();
                mmGhiChu.Text = hd.GhiChu.ToString();

                var ctdh = (from ct in this.context.CTDonHangs
                           join t in this.context.Thuocs on ct.MaThuoc equals t.Id
                           join dv in this.context.DonVis on ct.MaDonVi equals dv.Id
                           where ct.MaDonHang == hd.Id
                           select new
                           {
                               MaThuoc = t.Id,
                               TenThuoc = t.TenThuoc,
                               SoLuong = ct.SoLuong,
                               DonVi = dv.TenDonVi
                           }).ToList();

                foreach (var item in ctdh) 
                { 
                    var r = this.table.NewRow();
                    r.ItemArray = new object[] { 
                        item.MaThuoc, item.TenThuoc, item.SoLuong, item.DonVi
                    };
                    this.table.Rows.Add(r);
                }

                this.gridControl1.DataSource = table;
                //this.teThanhTien.EditValue = ThanhTien;

                return;
                
            }

            MessageBox.Show("Khách hàng không có hóa đơn");
        }

        private void b8Reset_Click(object sender, EventArgs e)
        {
            InitTable();
            this.cbGoiThuoc.Text = string.Empty;
            cbKhachHang.Text = string.Empty;
            this.cbMaThuoc.Text = string.Empty;
            this.cbTenThuoc.Text = string.Empty;
            this.calcSoLuong.Text = string.Empty;
            this.cbDvt.Text = "Viên";
            this.cbKhachHang.Text = string.Empty;
            this.txtNamSinh.Text = string.Empty;
            this.mmGhiChu.Text = string.Empty;
            this.teThanhTien.Text = string.Empty;
            this.teSoTien.Text = string.Empty;
            this.cbKhachHang.Focus();
            DoCleanup();
            
        }

        private void cbTenThuoc_Properties_KeyDown(object sender, KeyEventArgs e)
        {
           
        }

        private void btThemMoi_Click(object sender, EventArgs e)
        {
            DoInsert();
        }
        public void Blank()
        {
            cbGoiThuoc.Text = "";
            cbKhachHang.Text = "";
            txtNamSinh.Text = "";
            calcSoLuong.Text = "";
            teThanhTien.Text = "";
            mmGhiChu.Text = "";
        }


        private void mmGhiChu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Tab) {
                this.cbMaThuoc.Focus();
                //e.Handled = true;
            }
        }

        private void txtNamSinh_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab) SendKeys.Send("{Tab}{F4}");
        }

        private void cbTenThuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab) SendKeys.Send("{Tab}{F4}");
        }

        private void cbMaThuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab) SendKeys.Send("{Tab}{F4}");
        }

        private void cbKhachHang_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            
        }

        private void cbKhachHang_Properties_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            //var lk = (LookUpEdit)sender;
            //e.DisplayText = lk.Text;
        }

        private void cbKhachHang_Properties_ProcessNewValue(object sender, ProcessNewValueEventArgs e)
        {
            
        }

        private void cbKhachHang_GetNotInListValue(object sender, GetNotInListValueEventArgs e)
        {
            
        }

        private void cbKhachHang_ProcessNewValue(object sender, ProcessNewValueEventArgs e)
        {
            var lk = (LookUpEdit)sender;

            if (e.DisplayValue == null || string.Empty.Equals(e.DisplayValue))
                return;

            var newKh = new KhachHang { 
                TenKhachHang = lk.Text
            };

            var list = (List<KhachHang>)lk.Properties.DataSource;
            this.CleanUpList(list);
            list.Add(newKh);

            lk.Properties.DataSource = list;

            e.Handled = true;
        }

        private void CleanUpList(List<KhachHang> list)
        {
            for (int i = list.Count - 1; i >= 0; i--)
            {
                if (list[i].NamSinh == null)
                {
                    list.RemoveAt(i);
                }
            }
        }

        private void cbKhachHang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab) SendKeys.Send("{Tab}{F4}");
        }

        private void btThemMoi_Load(object sender, EventArgs e)
        {

        }

    }
}